package com.iagent.request.apache;

import com.iagent.logging.LogFactory;
import com.iagent.logging.Logger;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liujieyu
 * @date 2022/12/14 15:59
 * @desciption single http request
 */
public class ApacheSingleHttpClientExecutor extends AbstractApacheHttpExecutor {

    private static final Logger logger = LogFactory.getLogger(ApacheSingleHttpClientExecutor.class);

    private Map<String, RequestConfig> configMap = new ConcurrentHashMap<>();

    @Override
    public CloseableHttpClient getHttpClient(String url, com.iagent.request.RequestConfig config) throws UnsupportedOperationException {
        String key = config.getConnectionTime() + String.valueOf(config.getReadTime());
        RequestConfig requestConfig = null;
        if (configMap.containsKey(key)) {
            requestConfig = configMap.get(key);
        } else {
            requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(config.getConnectionTime())
                    .setConnectTimeout(config.getConnectionTime())
                    .setSocketTimeout(config.getReadTime())
                    .build();
            configMap.put(key, requestConfig);
        }

        CloseableHttpClient build = HttpClientBuilder.create()
                .setDefaultRequestConfig(requestConfig)
                .setSSLSocketFactory(getSslSocketFactory())
                .setRetryHandler(new CommonHttpRequestRetryHandler())
                .build();
        return build;
    }

    @Override
    public void releaseConnection(CloseableHttpClient httpClient) throws UnsupportedOperationException {
        try {
            httpClient.close();
        } catch (IOException e) {
            logger.error("The http client close error", e);
            throw new RuntimeException(e);
        }
    }

}
